<?php
namespace app\index\controller;

use app\BaseController;
use app\index\service\DyOpenService;
use app\index\service\KsOpenService;
use app\index\service\RedisLock;
use Firebase\JWT\JWT;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;

class Login extends BaseController
{
    /**
     * 抖音登录
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dyQuickLogin(){
        validateParam('code','code');
        $code=input('code');//获取的登录code
        $encryptedData=input('encryptedData');
        $iv=input('iv');
        $service = new DyOpenService();
        $result = $service->login($code);
//        $result = $service->getPhone($code,$encryptedData,$iv);
        //        $redisLock = new RedisLock();
        //        $loginKey = 'UserLogin-'.$result['phoneNumber'];
        //        $is_lock = $redisLock->lock($loginKey, 5);
        //        while ($is_lock === false) {
        //            // 获取锁
        //            $is_lock = $redisLock->lock($loginKey, 5);
        //        }
        //首先判断用户是否已经注册了
        $user=Db::name('user')
            ->where('dy_openid',$result['openid'])
            ->where('is_deleted',0)
            ->find();
        if(!empty($user)){
            //更新用户的抖音的openid
            Db::name('user')
                ->where('id',$user['id'])
                ->update(['dy_openid'=>$result['openid']]);
            //获取登录的token
            $expire_time = strtotime('+100 day');
            $token_arr = [
                'user_id' => $user['id'],
                'expire_time' => $expire_time//token的过期时间为十天
            ];
            $key = config('system.tokenKey');
            $jwt_token = JWT::encode($token_arr, $key);
            //$redisLock->unlock($loginKey);
            return success('登录成功',['token'=>$jwt_token]);
        }else{
            //开始创建用户
            $data['dy_openid'] = $result['openid'];
            $data['avatar'] = '';
            $data['phone'] = $result['phoneNumber'] ?? '';
            $data['province'] = input('province');//所在省份
            $data['city'] = input('city');//定位的城市
            $data['platform'] = 'dy';
            $data['update_at'] = currentTime();
            $data['create_at'] = currentTime();
            $user_id = Db::name('user')
                ->insertGetId($data);
            //获取用户的邀请码
            $invite_code = base_convert($user_id, 10, 36);
            $nickname = '新用户' . $invite_code;
            //更新用户的邀请码
            Db::name('user')
                ->where('id', $user_id)
                ->update(['invite_code' => $invite_code, 'nickname' => $nickname]);
            //获取登录的token
            $expire_time = strtotime('+100 day');
            $token_arr = [
                'user_id' => $user_id,
                'expire_time' => $expire_time//token的过期时间为十天
            ];
            $key = config('system.tokenKey');
            $jwt_token = JWT::encode($token_arr, $key);

            //$redisLock->unlock($loginKey);
            return success('登录成功',['token'=>$jwt_token]);
        }
    }

    /**
     * 抖音登录
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function dyLogin(){
        validateParam('code,encryptedData,iv','code,encryptedData,iv');
        $code=input('code');//获取的登录code
        $encryptedData=input('encryptedData');
        $iv=input('iv');
        $service = new DyOpenService();
        //$result = $service->login($code);
        $result = $service->getPhone($code,$encryptedData,$iv);
//        $redisLock = new RedisLock();
//        $loginKey = 'UserLogin-'.$result['phoneNumber'];
//        $is_lock = $redisLock->lock($loginKey, 5);
//        while ($is_lock === false) {
//            // 获取锁
//            $is_lock = $redisLock->lock($loginKey, 5);
//        }
        //首先判断用户是否已经注册了
        $user=Db::name('user')
            ->where('phone',$result['phoneNumber'])
            ->where('is_deleted',0)
            ->find();
        if(!empty($user)){
            //更新用户的抖音的openid
            Db::name('user')
                ->where('id',$user['id'])
                ->update(['dy_openid'=>$result['openid']]);
            //获取登录的token
            $expire_time = strtotime('+100 day');
            $token_arr = [
                'user_id' => $user['id'],
                'expire_time' => $expire_time//token的过期时间为十天
            ];
            $key = config('system.tokenKey');
            $jwt_token = JWT::encode($token_arr, $key);
            //$redisLock->unlock($loginKey);
            return success('登录成功',['token'=>$jwt_token]);
        }else{
            //开始创建用户
            $data['dy_openid'] = $result['openid'];
            $data['avatar'] = '';
            $data['phone'] = $result['phoneNumber'];
            $data['province'] = input('province');//所在省份
            $data['city'] = input('city');//定位的城市
            $data['platform'] = 'dy';
            $data['update_at'] = currentTime();
            $data['create_at'] = currentTime();
            $user_id = Db::name('user')
                ->insertGetId($data);
            //获取用户的邀请码
            $invite_code = base_convert($user_id, 10, 36);
            $nickname = '新用户' . $invite_code;
            //更新用户的邀请码
            Db::name('user')
                ->where('id', $user_id)
                ->update(['invite_code' => $invite_code, 'nickname' => $nickname]);
            //获取登录的token
            $expire_time = strtotime('+100 day');
            $token_arr = [
                'user_id' => $user_id,
                'expire_time' => $expire_time//token的过期时间为十天
            ];
            $key = config('system.tokenKey');
            $jwt_token = JWT::encode($token_arr, $key);

            //$redisLock->unlock($loginKey);
            return success('登录成功',['token'=>$jwt_token]);
        }
    }


    /**
     * 微信登录
     * @return \think\response\Json
     * @throws Exception
     * @throws LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function wxLogin(){
        validateParam('code,iv,decode','code,iv,decode');
        $param = input();
        $code=input('code');//获取的登录code
        $config = config('system.weChatDeveloper');//小程序数据配置
        $mini = \WeMini\Crypt::instance($config);
        $weixin_user=$mini->session($code);
        if(isset($weixin_user['errcode'])){
            return error($weixin_user['errmsg']);
        }
        $config = config('system.weChatDeveloper');//小程序数据配置
        $mini = \WeMini\Crypt::instance($config);
        $phone_data=$mini->decode($param['iv'], $weixin_user['session_key'], $param['decode']);
        if(empty($phone_data['phoneNumber'])){
            return error('获取手机号失败');
        }
        $redisLock = new RedisLock();
        $key = 'UserLogin-'.$phone_data['phoneNumber'];
        $is_lock = $redisLock->lock($key, 5);
        while ($is_lock === false) {
            // 获取锁
            $is_lock = $redisLock->lock($key, 5);
        }
        $user = Db::name('user')
            ->where('is_deleted',0)
            ->where('phone',$phone_data['phoneNumber'])
            ->find();
        if(empty($user)) {
            //开始创建用户
            $data['wx_openid'] = $weixin_user['openid'];
            $data['avatar'] = 'https://lvpaiqiche.oss-cn-hangzhou.aliyuncs.com/image/20220523/20220523154705_yjgf.png';
            $data['phone'] = $phone_data['phoneNumber'];
            $data['platform'] = 'wx';
            $data['province'] = input('province');//所在省份
            $data['city'] = input('city');//定位的城市
            $data['update_at'] = currentTime();
            $data['create_at'] = currentTime();
            $user_id = Db::name('user')
                ->insertGetId($data);
            //获取用户的邀请码
            $invite_code = base_convert($user_id, 10, 36);
            $nickname = '新用户' . $invite_code;
            //更新用户的邀请码
            Db::name('user')
                ->where('id', $user_id)
                ->update(['invite_code' => $invite_code, 'nickname' => $nickname]);
        }else{
            $user_id = $user['id'];
            Db::name('user')
                ->where('id', $user_id)
                ->update(['wx_openid'=>$weixin_user['openid']]);
        }
        //获取登录的token
        $expire_time = strtotime('+150 day');
        $token_arr = [
            'user_id' => $user_id,
            'expire_time' => $expire_time//token的过期时间为十天
        ];
        $key = config('system.tokenKey');
        $jwt_token = JWT::encode($token_arr, $key);
        $redisLock->unlock($key);
        return success('登录成功',['token'=>$jwt_token]);
    }




    /**
     * 快手登录
     * @return \think\response\Json
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function ksLogin(){
        validateParam('code,encryptedData,iv','code,encryptedData,iv');
        $code=input('code');//获取的登录code
        $encryptedData=input('encryptedData');
        $iv=input('iv');
        $service = new KsOpenService();
        $result = $service->getPhone($code,$encryptedData,$iv);
        $redisLock = new RedisLock();
        $loginKey = 'UserLogin-'.$result['phoneNumber'];
        $is_lock = $redisLock->lock($loginKey, 5);
        while ($is_lock === false) {
            // 获取锁
            $is_lock = $redisLock->lock($loginKey, 5);
        }
        //首先判断用户是否已经注册了
        $user=Db::name('user')
            ->where('phone',$result['phoneNumber'])
            ->where('is_deleted',0)
            ->find();
        if(!empty($user)){
            //更新用户的抖音的openid
            Db::name('user')
                ->where('id',$user['id'])
                ->update(['ks_openid'=>$result['open_id']]);
            //获取登录的token
            $expire_time = strtotime('+100 day');
            $token_arr = [
                'user_id' => $user['id'],
                'expire_time' => $expire_time//token的过期时间为十天
            ];
            $key = config('system.tokenKey');
            $jwt_token = JWT::encode($token_arr, $key);
            $redisLock->unlock($loginKey);
            return success('登录成功',['token'=>$jwt_token]);
        }else{
            //开始创建用户
            $data['ks_openid'] = $result['open_id'];
            $data['avatar'] = 'https://lvpaiqiche.oss-cn-hangzhou.aliyuncs.com/image/20220523/20220523154705_yjgf.png';
            $data['phone'] = $result['phoneNumber'];
            $data['province'] = input('province');//所在省份
            $data['city'] = input('city');//定位的城市
            $data['platform'] = 'ks';
            $data['update_at'] = currentTime();
            $data['create_at'] = currentTime();
            $user_id = Db::name('user')
                ->insertGetId($data);
            //获取用户的邀请码
            $invite_code = base_convert($user_id, 10, 36);
            $nickname = '新用户' . $invite_code;
            //更新用户的邀请码
            Db::name('user')
                ->where('id', $user_id)
                ->update(['invite_code' => $invite_code, 'nickname' => $nickname]);
            //获取登录的token
            $expire_time = strtotime('+100 day');
            $token_arr = [
                'user_id' => $user_id,
                'expire_time' => $expire_time//token的过期时间为十天
            ];
            $key = config('system.tokenKey');
            $jwt_token = JWT::encode($token_arr, $key);

            $redisLock->unlock($loginKey);
            return success('登录成功',['token'=>$jwt_token]);
        }
    }




    /**
     * 考试小程序用户协议和隐私政策
     * @return \think\response\Json
     */
    public function testPolicyAndAgreement(){
        $content1=Db::name('system_content_setting')
            ->where(['key'=>'test_privacy_policy'])
            ->value('value');
        $content2=Db::name('system_content_setting')
            ->where(['key'=>'test_user_agreement'])
            ->value('value');
        $data['privacy_policy']=$content1;
        $data['user_agreement']=$content2;
        $data['test_driver_agreement'] = Db::name('system_content_setting')
            ->where(['key'=>'test_driver_agreement'])
            ->value('value');

        $data['bole_user_agreement'] = Db::name('system_content_setting')
            ->where(['key'=>'bole_user_agreement'])
            ->value('value');
        return success('考试小程序隐私政策和用户协议',$data);
    }

    public function test(){
    }

}
